package org.jeecg.modules.sggg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.*;
import org.jeecg.modules.sggg.service.*;
import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Description: 健康币操作记录
 * @Author: jeecg-boot
 * @Date: 2023-03-30
 * @Version: V1.0
 */
@Api (tags = "健康币操作记录")
@RestController
@RequestMapping ("/operationRecords/sgOperationRecords")
@Slf4j
public class SgOperationRecordsController extends JeecgController<SgOperationRecords, ISgOperationRecordsService> {

    @Autowired
    private ISgOperationRecordsService sgOperationRecordsService;

    @Autowired
    private ISgItemTypeService sgItemTypeService;

    @Autowired
    private ISgItemService sgItemService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISgTaskService sgTaskService;

    @Autowired
    private  ISgDeviceRelevanceService sgDeviceRelevanceService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysRoleController sysRoleController;

    @Autowired
    private ISysDepartService sysDepartController;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "健康币操作记录-分页列表查询")
    @ApiOperation (value = "健康币操作记录-分页列表查询", notes = "健康币操作记录-分页列表查询")
    @GetMapping (value = "/list")
    public Result<IPage<SgOperationRecords>> queryPageList (@RequestParam (name = "type") int type,
                                                            String name,
                                                            String createTime,
                                                            String closureTime,
                                                            @RequestParam (name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam (name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        System.out.println(responsibleAgencies);
        if(sysDepart !=null && sysDepart.getDeptAttr()!=null){
            // 1.三高之家
            if(sysDepart.getDeptAttr().equals("1")){
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if(sysDepart.getDeptAttr().equals("2")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgSigningRecord.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if(sysDepart.getDeptAttr().equals("3")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgSigningRecord.setResponsibleAgencies(responsibleAgencies);
            }
        }else{
            sysUser.setId(sysUser1.getId());
        }
        SgOperationRecords sgOperationRecords = new SgOperationRecords();
        sgOperationRecords.setType(type);
        Page<SgOperationRecords> page = new Page<SgOperationRecords>(pageNo, pageSize);
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        IPage<SgOperationRecords> pageList = sgOperationRecordsService.doctorAuthority(page, sysUser.getId(),responsibleAgencies, type, sysUser.getOrgCode(), name,closureTime,createTime, roleCode);
        return Result.OK(pageList);
    }

    /**
     * 健康币总和
     *
     * @param
     * @return
     */
    @ApiOperation (value = "健康币操作记录-健康币总和", notes = "健康币操作记录-健康币总和")
    @GetMapping (value = "/numberCount")
    public Result<SgOperationRecords> numberCount (@RequestParam (name = "type") int type,
                                                   String name,
                                                   String createTime,
                                                   String closureTime) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SgOperationRecords pageList = sgOperationRecordsService.numberCount(sysUser.getId(), type, sysUser.getOrgCode(), name,closureTime,createTime, roleCode);
        return Result.OK(pageList);
    }


    /**
     * 根据居民id查询已经兑换的商品列表
     *
     * @param mid 居民id
     * @return 商品列表
     */
    @GetMapping ("/queryPrizeListByMid")
    public Result<List<SgOperationRecords>> queryListByMid (String mid, String isMake) {
        List<SgOperationRecords> list = sgOperationRecordsService.prizeList(mid, isMake);
        return Result.OK(list);
    }

    /**
     * 添加
     *
     * @param sgOperationRecords
     * @return
     */
    @AutoLog (value = "健康币操作记录-添加")
    @ApiOperation (value = "健康币操作记录-添加", notes = "健康币操作记录-添加")
    //@RequiresPermissions("operationRecords:sg_operation_records:add")
    @PostMapping (value = "/add")
    public Result<String> add (@RequestBody SgOperationRecords sgOperationRecords) {
        sgOperationRecordsService.save(sgOperationRecords);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sgOperationRecords
     * @return
     */
    @AutoLog (value = "健康币操作记录-编辑")
    @ApiOperation (value = "健康币操作记录-编辑", notes = "健康币操作记录-编辑")
    //@RequiresPermissions("operationRecords:sg_operation_records:edit")
    @RequestMapping (value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit (@RequestBody SgOperationRecords sgOperationRecords) {
        sgOperationRecordsService.updateById(sgOperationRecords);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog (value = "健康币操作记录-通过id删除")
    @ApiOperation (value = "健康币操作记录-通过id删除", notes = "健康币操作记录-通过id删除")
    //@RequiresPermissions("operationRecords:sg_operation_records:delete")
    @DeleteMapping (value = "/delete")
    public Result<String> delete (@RequestParam (name = "id", required = true) String id) {
        sgOperationRecordsService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog (value = "健康币操作记录-批量删除")
    @ApiOperation (value = "健康币操作记录-批量删除", notes = "健康币操作记录-批量删除")
    //@RequiresPermissions("operationRecords:sg_operation_records:deleteBatch")
    @DeleteMapping (value = "/deleteBatch")
    public Result<String> deleteBatch (@RequestParam (name = "ids", required = true) String ids) {
        this.sgOperationRecordsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "健康币操作记录-通过id查询")
    @ApiOperation (value = "健康币操作记录-通过id查询", notes = "健康币操作记录-通过id查询")
    @GetMapping (value = "/queryById")
    public Result<SgOperationRecords> queryById (@RequestParam (name = "id", required = true) String id) {
        SgOperationRecords sgOperationRecords = sgOperationRecordsService.getById(id);
        if (sgOperationRecords == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgOperationRecords);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgOperationRecords
     */
    //@RequiresPermissions("operationRecords:sg_operation_records:exportXls")
    @RequestMapping (value = "/exportXls")
    public ModelAndView exportXls (HttpServletRequest request, SgOperationRecords sgOperationRecords) {
        return super.exportXls(request, sgOperationRecords, SgOperationRecords.class, "健康币操作记录");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("operationRecords:sg_operation_records:importExcel")
    @RequestMapping (value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel (HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgOperationRecords.class);
    }

    /**
     * 根据居民获取健康币操作记录
     *
     * @param memberId
     * @return
     */
    @GetMapping ("/getOperationRecordsByMId")
    public Result<List<SgOperationRecords>> getOperationRecordsByMId (String memberId, Integer type) {
        List<SgOperationRecords> sgOperationRecords = sgOperationRecordsService.getOperationRecordsByMId(memberId, type);
        return Result.ok(sgOperationRecords);
    }

    //region 健康任务-日常测量项测量

    /**
     * 每日测量任务
     *
     * @param typeName
     * @param type
     * @param memberId
     * @throws Exception
     */
    public void dailyMeasurementTask (String typeName, Integer type, String memberId) throws Exception {
        SgMember sgMember = sgMemberService.getById(memberId);
        // 查询任务类型为日常血压/血糖测量的任务
        SgItemType sgItemType = sgItemTypeService.getOne(new QueryWrapper<SgItemType>().eq("name", typeName).eq("sys_org_code", sgMember.getSysOrgCode()));
        if (sgItemType != null) {
            boolean isBetween = false;
            // 查询该任务详情
            SgItem sgItem = sgItemService.getOne(new QueryWrapper<SgItem>().eq("item_id", sgItemType.getId()).eq("is_on_sale", 1).like("name", type == 0 ? "血压" : "血糖"));
            if (sgItem != null) {
                if (StringUtils.isNotBlank(sgItem.getPeriodTime())) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
                    LocalTime now = LocalTime.now();
                    // 获取当前的时分
                    LocalTime current = LocalTime.parse(now.getHour() + ":" + now.getMinute(), formatter);
                    ObjectMapper mapper = new ObjectMapper();
                    List<TaskPeriodTime> periods = mapper.readValue(sgItem.getPeriodTime(), new TypeReference<List<TaskPeriodTime>>() {
                    });
                    // 判断本次测量的时间是否符合该任务的时间段范围
                    for (TaskPeriodTime period : periods) {
                        LocalTime start = LocalTime.parse(period.getStartPeriodTime(), formatter);
                        LocalTime end = LocalTime.parse(period.getEndPeriodTime(), formatter);
                        isBetween = current.isAfter(start) && current.isBefore(end);
                        if (isBetween) {
                            break;
                        }
                    }
                } else {
                    isBetween = true;
                }
                if (isBetween) {
                    // 是否满足任务的期次
                    if (!isSatisfyPeriod(sgItem, memberId)) {
                        SgTask task = new SgTask();
                        task.setItemId(sgItem.getId());
                        task.setMemberId(memberId);
                        task.setStatus(1);
                        sgTaskService.save(task);
                        isSatisfyPeriod(sgItem, memberId);
                    }
                }
            }
        }
    }

    /**
     * 每日测量任务-是否满足任务期次
     *
     * @param sgItem
     * @param memberId
     * @return
     */
    public Boolean isSatisfyPeriod (SgItem sgItem, String memberId) {
        long count = 0L;
        QueryWrapper<SgTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("item_id", sgItem.getId()).eq("member_id", memberId);
        count = sgTaskService.count(queryWrapper.last("and TO_DAYS(create_time) = TO_DAYS(NOW())"));
        if (sgItem.getPeriod() == count) {
            // 查询该条任务在今天是否完成
            Long isOKCount = sgOperationRecordsService.count(new QueryWrapper<SgOperationRecords>().eq("member_id", memberId).eq("task_id", sgItem.getId()).last("and TO_DAYS(create_time) = TO_DAYS(NOW())"));
            if (isOKCount == 0) {
                // 健康币操作记录表添加数据
                SgOperationRecords operationRecords = new SgOperationRecords();
                operationRecords.setMemberId(memberId);
                operationRecords.setType(0);
                operationRecords.setTaskId(sgItem.getId());
                operationRecords.setNumber(sgItem.getCurrency());
                sgOperationRecordsService.save(operationRecords);
                // 居民增加健康币
                SgMember member = sgMemberService.getById(memberId);
                member.setCurrency(member.getCurrency() + sgItem.getCurrency());
                sgMemberService.updateById(member);
            }
        } else {
            return false;
        }
        return true;
    }

    //endregion

    /**
     * 根据居民id健康币操作记录
     *
     * @param
     * @return
     */
    @ApiOperation (value = "根据居民id健康币操作记录", notes = "根据居民id健康币操作记录")
    @GetMapping (value = "/queryByMemberId")
    public Result<List<SgOperationRecords>> queryByMemberId (@RequestParam (name = "memberId", required = true) String memberId) {
        List<SgOperationRecords> sgOperationRecords = sgOperationRecordsService.list(new QueryWrapper<SgOperationRecords>().eq("member_id", memberId)
                .select("*", "(select name from sg_item where id = sg_operation_records.task_id) As taskName , (select name from sg_goods where id= sg_operation_records.goods_id)As goodsName"));
        if (sgOperationRecords == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgOperationRecords);
    }


    //region 绑定设备赠送50健康币

    /**
     * TODO     绑定设备赠送50健康币
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/5/10 10:16
     * @Exception
     */
    @GetMapping ("/addHealthCoins")
    public Result<Boolean> addHealthCoins () {
        //所有已绑定设备的人
        List<SgMember> sgMembers = sgMemberService.list(new QueryWrapper<SgMember>().eq("del_flag", "0").eq("sys_org_code","A02A01"));

        for (SgMember item : sgMembers) {
            List<SgDeviceRelevance> deviceRelevances = sgDeviceRelevanceService.list(new QueryWrapper<SgDeviceRelevance>().eq("member_id",item.getId()));
            if (deviceRelevances.size()>0) {
                log.info("********<--" + item.getName() + "健康币追加开始-->*********");
                SgTask sgTask = new SgTask();
                sgTask.setMemberId(item.getId());
                sgTask.setItemId("1656118442853412865");
                sgTask.setStatus(1);
                sgTaskService.save(sgTask);
                log.info("任务审核表追加完成");
                SgOperationRecords sgOperationRecords = new SgOperationRecords();
                sgOperationRecords.setMemberId(item.getId());
                sgOperationRecords.setType(0);
                sgOperationRecords.setTaskId("1656118442853412865");
                sgOperationRecordsService.save(sgOperationRecords);
                log.info("健康币操作记录追加完成");
                item.setDeviceId(null);
                int currency = 0;
                if (item.getCurrency()!=null) {
                    currency +=item.getCurrency();
                }
                item.setCurrency(currency + 50);
                sgMemberService.updateById(item);
                log.info("健康币追加完成");
                sgOperationRecordsService.updateById(sgOperationRecords);
                log.info("********<--" + item.getName() + "健康币追加完毕-->*********");
            }
        }
        return Result.OK(true);
    }

    //endregion

}
